package com.hcrazy.manchester.app.services;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hcrazy.manchester.app.form.ForumBatchForm;
import com.hcrazy.manchester.app.jdbc.AdvertDAO;
import com.hcrazy.manchester.app.jdbc.MessageDAO;
import com.hcrazy.manchester.app.jdbc.PostDAO;
import com.hcrazy.manchester.app.jdbc.TopicDAO;
import com.hcrazy.manchester.app.jdbc.UserDAO;
import com.hcrazy.manchester.app.pojo.Advert;
import com.hcrazy.manchester.app.pojo.ErrorMsg;
import com.hcrazy.manchester.app.pojo.ForumRule;
import com.hcrazy.manchester.app.pojo.Image;
import com.hcrazy.manchester.app.pojo.Message;
import com.hcrazy.manchester.app.pojo.PageModel;
import com.hcrazy.manchester.app.pojo.Post;
import com.hcrazy.manchester.app.pojo.Topic;
import com.hcrazy.manchester.app.pojo.User;
import com.hcrazy.manchester.app.pojo.UserGroup;
import com.hcrazy.manchester.app.utils.Constant;

public class TopicService {

	private TopicDAO topicDAO;
	
	private PostDAO postDAO;
	
	private UserDAO userDAO;
	
	private AdvertDAO advertDAO;
	
	private MessageDAO messageDAO;
	
	public MessageDAO getMessageDAO() {
		return messageDAO;
	}

	public void setMessageDAO(MessageDAO messageDAO) {
		this.messageDAO = messageDAO;
	}

	public AdvertDAO getAdvertDAO() {
		return advertDAO;
	}

	public void setAdvertDAO(AdvertDAO advertDAO) {
		this.advertDAO = advertDAO;
	}

	public PostDAO getPostDAO() {
		return postDAO;
	}

	public void setPostDAO(PostDAO postDAO) {
		this.postDAO = postDAO;
	}

	public TopicDAO getTopicDAO() {
		return topicDAO;
	}

	public void setTopicDAO(TopicDAO topicDAO) {
		this.topicDAO = topicDAO;
	}

	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	/**
	 * 发表主题
	 * @param topic
	 * @return
	 * @throws Exception
	 */
	public Object addTopic(Topic topic) throws Exception{
		
		System.out.println(topic.getAppointDemand());
		
		if(topic.getForumId() == 2){
			topic.setPostDate(System.currentTimeMillis()/1000);
			topic.setLastPost(topic.getPostDate());
			topic.setLastPoster(topic.getAuthor());
			
			if(null != topic && topic.getPraiseBaseCount() > 0){
				topic.setPraiseCount(topic.getPraiseBaseCount());
			}
			if(null != topic && topic.getCommentBaseCount() > 0){
				topic.setCommentCount(topic.getCommentBaseCount());
			}
			topicDAO.addTopic(topic);
			
			return null;
		}
		
		//增加验证功能，强制客户端遵循
		if(topic.getForumId() <= 0){
			return new ErrorMsg(Constant.TOPIC_FORUMID_NULL,"所属论坛版块ID为空！");
		}
		if(null == topic.getSubject()|| "".equals(topic.getSubject())){
			return new ErrorMsg(Constant.TOPIC_SUBJECT_NULL,"主题标题为空！");
		}
		if(null == topic.getMessage() || "".equals(topic.getMessage())){
			return new ErrorMsg(Constant.TOPIC_MESSAGE_NULL,"主题内容为空！");
		}
		
		topic.setPostDate(System.currentTimeMillis()/1000);
		topic.setLastPost(topic.getPostDate());
		topic.setLastPoster(topic.getAuthor());
		
		if(null != topic && topic.getPraiseBaseCount() > 0){
			topic.setPraiseCount(topic.getPraiseBaseCount());
		}
		if(null != topic && topic.getCommentBaseCount() > 0){
			topic.setCommentCount(topic.getCommentBaseCount());
		}
		
		topicDAO.addTopic(topic);
		
		//添加主题成功，相应增加一条回帖
		Post post = new Post();
		post.setForumId(topic.getForumId());
		post.setTopicId(topicDAO.getIncreamentId());
		post.setFirst(Constant.POST_FIRST_YES);
		post.setAuthor(topic.getAuthor());
		post.setAuthorId(topic.getAuthorId());
		post.setSubject(topic.getSubject());
		post.setMessage(topic.getMessage());
		post.setPostDate(topic.getPostDate());
		post.setPostIp(topic.getUserIp());
		
		postDAO.addPost(post);
		
		Map<String,String> result = new HashMap<String,String>();
		result.put(Constant.SINGLE_RETURN,"true");
		
		User user = userDAO.getUserById(topic.getAuthorId());
		
		//增加用户经验值
		setUserRule(user,Constant.RULE_TYPE_TOPIC);
		
		return result;
	}
	
	public void updateTopic(Topic topic) throws Exception {
		if(null == topic)
			return;
		long topicId = topic.getTopicId();
		topic.setLastPost(System.currentTimeMillis()/1000);
		
		topic.setPraiseCount(topic.getPraiseCount() + topic.getPraiseBaseCount());
		topic.setCommentCount(topic.getCommentCount() + topic.getCommentBaseCount());
		
		topicDAO.updateTopic(topic);
		
		if(topic.getAdvertStr() != null && !topic.getAdvertStr().equals("")){
			Gson gson = new Gson();
			Type type = new TypeToken<Advert>(){}.getType();
			Advert ad = gson.fromJson(topic.getAdvertStr(),type);
			if(null != ad && ad.getAdContent() != null && !ad.getAdContent().equals("")){
				advertDAO.deleteAdvert(topicId,Constant.COMM_BBS_INFO_MODULE);
				
				ad.setModuleId(topicId);
				ad.setModuleType(Constant.COMM_BBS_INFO_MODULE);
				advertDAO.addAdvert(ad);
			}
			
		}
	}
	
	/**
	 * 后台获取主题列表
	 * @param model 分页信息
	 * @param forumId 所属板块
	 * @param authors 作者们
	 * @param title 标题关键字
	 * @param startTime 发表时间起始
	 * @param endTime   发表时间截止
	 * @return
	 * @throws Exception
	 */
	public PageModel getTopics(PageModel model,int forumId,String authors,String title,String startTime,String endTime,int type,int sortId) throws Exception{
		long start = 0;
		long end = 0;
		if(null != startTime && !"".equals(startTime)){
			if(null != endTime && !"".equals(endTime)){
				DateTime dt1 = DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime(startTime);
				DateTime dt2 = DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime(endTime);
				start = dt1.getMillis()/1000;
				end = dt2.getMillis()/1000;
				
			}
		}
		PageModel result = topicDAO.getPagedInfos(model, forumId, authors, title, start, end,type,sortId);
		if(null != result && !result.getResult().isEmpty()){
			for(Object obj : result.getResult()){
				if(obj instanceof Topic){
					Topic topic = (Topic)obj;
					DateTime dt = new DateTime(topic.getLastPost()*1000);
					topic.setLastPostDate(dt.toString("yyyy-MM-dd HH:mm"));
					
				}
			}
		}
		return result;
	}
	
	/**
	 * 客户端获取主题列表
	 * @param pageModel
	 * @param type
	 * @param forumId
	 * @return
	 * @throws Exception
	 */
	public PageModel getTopics(PageModel pageModel,int typeMode,int forumId,int type) throws Exception{
		PageModel model = topicDAO.getPagedInfos(pageModel, typeMode, forumId,type);
		if(null != model && !model.getResult().isEmpty()){
			for(int i=0;i<model.getResult().size();i++){
				Topic topic = (Topic)(model.getResult().get(i));
				String images = topic.getImages();
				topic.setImgs(this.setImageJson(images));
			}
		}
		return model;
	}
	
	private List<Image> setImageJson(String images){
		String[] imgArray = images.split(",");
		List<Image> imgs = new ArrayList<Image>();
		for(String img:imgArray){
			int index = img.indexOf("_");
			int lastIndex = img.indexOf("__");
			int pointIndex = img.lastIndexOf(".");
			int width = 0;
			int height = 0;
			if(index > 0 && lastIndex > 0){
				width = Integer.parseInt(img.substring(index+1,lastIndex));
				height = Integer.parseInt(img.substring(lastIndex+2,pointIndex));
			}else if(index > 0 && lastIndex <= 0){
				width = Integer.parseInt(img.substring(index+1,pointIndex));
			}else if(index <= 0 && lastIndex > 0){
				height = Integer.parseInt(img.substring(lastIndex+2,pointIndex));
			}
			Image image = new Image(img,width,height);
			imgs.add(image);
		}
		
		return imgs;
		
	}
	
	public List<Topic> getHotTopics(int size) throws Exception{
		return topicDAO.getHotTopics(size, 0);
	}
	
	/**
	 * 主题批量设置
	 * @param form
	 * @throws Exception
	 */
	public void batch(ForumBatchForm form) throws Exception{
		int batchOption = form.getBatchOption();
		switch(batchOption){
			case Constant.TOPIC_BATCH_1:
				//批量移动版块
				topicDAO.batchMoveForum(form.getTopicIds(), form.getForumId());
				break;
			case Constant.TOPIC_BATCH_2:
				//批量置顶
				topicDAO.batchSetTopicUp(form.getTopicIds(), form.getUpOption());
				
				if(null != form.getTopicIds() && form.getTopicIds().length > 0){
					for(String topicId:form.getTopicIds()){
						if(null == topicId || topicId.equals(""))
							continue;
						long id = Long.parseLong(topicId);
						Topic topic = topicDAO.getById(id);
						User user = userDAO.getUserById(topic.getAuthorId());
						//增加用户经验值
						setUserRule(user,Constant.RULE_TYPE_TOP);
					}
				}
				
				
				break;
			case Constant.TOPIC_BATCH_3:
				//批量打开关闭
				topicDAO.batchClose(form.getTopicIds(), form.getClosedOption());
				break;
			case Constant.TOPIC_BATCH_4:
				if(null != form.getTopicIds() && form.getTopicIds().length > 0){
					for(String topicId:form.getTopicIds()){
						if(null == topicId || topicId.equals(""))
							continue;
						long id = Long.parseLong(topicId);
						Topic topic = topicDAO.getById(id);
						User user = userDAO.getUserById(topic.getAuthorId());
						//减少用户经验值
						setUserRule(user,Constant.RULE_TYPE_TOPIC,true);
					}
				}
				//批量删除回帖
				postDAO.batchDelete(form.getTopicIds(), form.getDelOption());
				//批量删除主题
				topicDAO.batchDelete(form.getTopicIds(), form.getDelOption());
				
				
				
				break;
			case Constant.TOPIC_BATCH_5:
				//批量设置精华
				topicDAO.batchSetTopicDigest(form.getTopicIds(), form.getDigestOption());
				if(null != form.getTopicIds() && form.getTopicIds().length > 0){
					for(String topicId:form.getTopicIds()){
						if(null == topicId || topicId.equals(""))
							continue;
						long id = Long.parseLong(topicId);
						Topic topic = topicDAO.getById(id);
						User user = userDAO.getUserById(topic.getAuthorId());
						//增加用户经验值
						setUserRule(user,Constant.RULE_TYPE_GOOD);
					}
				}
				break;
		}
	}
	
	/**
	 * 浏览主题帖子
	 * @param topicId
	 * @return
	 * @throws Exception
	 */
	public List<Post> viewTopic(long topicId) throws Exception{
		List<Post> posts = postDAO.getPostsByTopicId(topicId);
		
		return posts;
	}
	
	/**
	 * 回复主题帖子
	 * @param topicId
	 * @return
	 * @throws Exception
	 */
	public Object replyTopic(long topicId,int forumId,String message,
			String author,long authorId,String userIp,int anonymous) throws Exception{
		//增加验证功能，强制客户端遵循
		if(forumId <= 0){
			return new ErrorMsg(Constant.POST_FORUM_ID_NULL,"所属论坛版块ID为空！");
		}
		
		if(topicId <= 0){
			return new ErrorMsg(Constant.POST_TOPIC_ID_NULL,"所属主题ID为空！");
		}
		
		if(null == message || "".equals(message)){
			return new ErrorMsg(Constant.POST_MESSAGE_NULL,"回复内容为空！");
		}
		
		Post post = new Post();
		post.setForumId(forumId);
		post.setTopicId(topicId);
		post.setFirst(Constant.POST_FIRST_NO);
		post.setAuthor(author);
		post.setAuthorId(authorId);
		post.setMessage(message);
		post.setPostDate(System.currentTimeMillis()/1000);
		post.setPostIp(userIp);
		post.setAnonymous(anonymous);
		
		postDAO.addPost(post);
		
		User user = userDAO.getUserById(authorId);
		
		//增加用户经验值
		setUserRule(user,Constant.RULE_TYPE_REPLY);
		
		Topic topic = topicDAO.getById(topicId);
		
		//发送消息告知楼主
		DateTime dt = new DateTime();
		String time = dt.toString("yyyy-MM-dd HH:mm:ss");
		Message msg = new Message();
		msg.setFromUserId(0);//系统发出
		msg.setFromUserName("系统提醒");
		msg.setMessage("会员 "+ author + " 在 " + time + "回复了您的帖子！");
		msg.setMessageType(Constant.MESSAGE_TYPE_SYSTEM_REMIND);
		msg.setSendTime(time);
		msg.setToUserId(topic.getAuthorId());
		msg.setToUserName(topic.getAuthor());
		msg.setSendType(Constant.MESSAGE_TYPE_SYSTEM_REMIND);
		
		messageDAO.addMessage(msg);
		
		//更新主题回复数
		topicDAO.addReplyCount(topicId);
		
		return true;
	}
	
	public PageModel getMyTopics(PageModel model,long authorId) throws Exception{
		return topicDAO.getMyTopics(model, authorId);
	}
	
	public PageModel getMyPosts(PageModel model,long authorId) throws Exception{
		return postDAO.getMyPosts(model, authorId);
	}
	
	public void setViews(long id) throws Exception{
		//获取对象
		Topic secondary = topicDAO.getById(id);
		long views = secondary.getViews()+1;
		//计数+1
		topicDAO.setViews(views,id);
	}
	
	public  void setUserRule(User user,int ruleType) throws Exception{
		setUserRule(user,ruleType,false);//正数
	}
	
	public  void setUserRule(User user,int ruleType,boolean isDelete) throws Exception{
		if(null == user)
			return;
		//注册，增加经验值；增加卡包容量；增加用户组
		Map<Integer,ForumRule> rules = InitService.forumRules;
		ForumRule rule = rules.get(ruleType);
		if(null != rule && rule.getDisabled() == 0){
			if(isDelete){
				user.setExp(user.getExp() - rule.getRuleValue());//减少经验值
			}else{
				user.setExp(user.getExp() + rule.getRuleValue());//增加经验值
			}
			user.setBagCount(user.getExp() * Constant.BAG_S);//增加卡包容量
		}
		//设置用户组
		for(UserGroup group:InitService.userGroups){
			if(user.getExp() >= group.getExpLowerLimit() && user.getExp() <= group.getExpUperLimit()){
				user.setGroupId(group.getGroupId());
				user.setGroupName(group.getGroupName());
				break;
			}
		}
		
		userDAO.setUserExp(user);
	}
	
	public Topic getTopicById(long topicId) throws Exception {
		Topic topic = topicDAO.getById(topicId);
		DateTime dt = new DateTime(topic.getLastPost()*1000);
		topic.setLastPostDate(dt.toString("yyyy-MM-dd HH:mm"));
		Advert advert = advertDAO.getAdvert(topicId,Constant.COMM_BBS_INFO_MODULE);
		if(null != advert)
			topic.setAdvert(advert);
		return topic;
	}
	
	public PageModel getTopicsByCityId(PageModel model,int cityId) throws Exception{
		return topicDAO.getTopicsByCityId(model, cityId);
	}
	
	public void delTopic(long topicId) throws Exception{
		topicDAO.delTopic(topicId);
	}
}
